package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.cssy.xxkj.basic.entity.BasicMaterialsTypeDO;
import com.cssy.xxkj.logic.dao.LogicWarehouseDetailsDAO;
import com.cssy.xxkj.logic.dao.LogicWarehouseInventoryDAO;
import com.cssy.xxkj.logic.dao.LogicWarehousePriceDetailsDAO;
import com.cssy.xxkj.logic.dao.LogicWhCheckTaskDAO;
import com.cssy.xxkj.logic.entity.LogicWarehousePriceDetailsDO;
import com.cssy.xxkj.logic.entity.vo.LogicWarehouseEndMonthSumVO;
import com.cssy.xxkj.logic.service.ILogicReportsUtilService;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;

@Service("logicReportsUtilService")
public class LogicReportsUtilServiceImpl implements ILogicReportsUtilService{
	
	//成品仓库id
	private static final String prod_wh_id = "0003";
	
	private static final int p_scale = 2;
	
	@Resource(name = "oftenMapUtil")
	private OftenMapUtil oftenMapUtil;
	//物料的平均价
	@Resource(name = "logicWarehousePriceDetailsDAO")
	private LogicWarehousePriceDetailsDAO logicWarehousePriceDetailsDAO;
	//出入库明细DAO
	@Resource(name = "logicWarehouseDetailsDAO")
	private LogicWarehouseDetailsDAO logicWarehouseDetailsDAO;
	//库存DAO
	@Resource(name = "logicWarehouseInventoryDAO")
	private LogicWarehouseInventoryDAO logicWarehouseInventoryDAO;
	//盘点DAO
	@Resource(name = "logicWhCheckTaskDAO")
	private LogicWhCheckTaskDAO logicWhCheckTaskDAO;
	
	@Override
	public SearchResult findQueryEndMonthToSummary(SearchConditions scs)
			throws SyBaseException {
		//处理查询条件
		Map<String, String> excelMap = new HashMap<String, String>();
		SearchConditions processScs = this.processSearchCond(scs, excelMap);
		SearchResult rs = new SearchResult(processScs);
		//所有出入库单据
		long ListTime = System.currentTimeMillis();
		List<LogicWarehouseEndMonthSumVO> gsEndList = logicWarehouseDetailsDAO.findQueryEndMonthToSummary(processScs);
		System.out.println("Query List Time = "+(System.currentTimeMillis()-ListTime)/1000);
		if(gsEndList==null){
			gsEndList = new ArrayList<LogicWarehouseEndMonthSumVO>();
		}
		//查询物料平均价
		long AvgTime = System.currentTimeMillis();
		Map<String, BigDecimal> priceMap = this.processMaterAvgPrice(processScs);
		System.out.println("Query Type Time = "+(System.currentTimeMillis()-AvgTime)/1000);
		//盘点(期初)数量
		long TaskTime = System.currentTimeMillis();
		Map<String, LogicWarehouseEndMonthSumVO> pdEndMap = this.processTaskToEndMonth(processScs, excelMap.get("canQueryExcel"));
		System.out.println("Query Type Time = "+(System.currentTimeMillis()-TaskTime)/1000);
		//库存(期末)数量
		long InvnTime = System.currentTimeMillis();
		Map<String, LogicWarehouseEndMonthSumVO> kcEndMap = this.processInventoryToEndMonth(processScs);
		System.out.println("Query Invn Time = "+(System.currentTimeMillis()-InvnTime)/1000);
		//查询产品系列
		scs.clearCondition();
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		long TypeTime = System.currentTimeMillis();
		Map<String , BasicMaterialsTypeDO> materTypeMap = oftenMapUtil.getMaterialTypeKeyMaterialCode(scs);
		System.out.println("Query Type Time = "+(System.currentTimeMillis()-TypeTime)/1000);
		Map<String, LogicWarehouseEndMonthSumVO> endMonthMap = new HashMap<String, LogicWarehouseEndMonthSumVO>();
		for(LogicWarehouseEndMonthSumVO gsEnd : gsEndList){
			if(gsEnd==null){
				continue;
			}
			if(!prod_wh_id.equals(gsEnd.getZdWhId())){
				gsEnd.setZdCompId(null);
				gsEnd.setZdCompCode(null);
				gsEnd.setZdCompName(null);
			}
			String keyCode = gsEnd.getZdMaterCode();
			BasicMaterialsTypeDO bsMaterType = materTypeMap.get(keyCode);
			if(bsMaterType==null){
				gsEnd.setZdMaterSery(null);
			}else{
				gsEnd.setZdMaterSery(bsMaterType.getZd002Name());
			}
			/*String keyStr = gsEnd.getZdWhId()+"_"+gsEnd.getPiCode()+"_"+gsEnd.getZdMaterId()+"_"
					+gsEnd.getZdMaterModel()+"_"+gsEnd.getZdMaterSize()+"_"+gsEnd.getZdMaterColor()+"_"
					+gsEnd.getZdMaterQuanlity();*/
			String keyStr = gsEnd.getZdWhId()+"_"+gsEnd.getZdMaterId()+"_";
			keyStr = keyStr + (StringUtils.isEmpty(gsEnd.getPiCode())?null:gsEnd.getPiCode())+"_";
			keyStr = keyStr + (StringUtils.isEmpty(gsEnd.getZdMaterModel())?null:gsEnd.getZdMaterModel())+"_";
			keyStr = keyStr	+ (StringUtils.isEmpty(gsEnd.getZdMaterSize())?null:gsEnd.getZdMaterSize())+"_";
			keyStr = keyStr	+ (StringUtils.isEmpty(gsEnd.getZdMaterColor())?null:gsEnd.getZdMaterColor())+"_";
			keyStr = keyStr	+ (StringUtils.isEmpty(gsEnd.getZdMaterQuanlity())?null:gsEnd.getZdMaterQuanlity());
			/*String priceStr = gsEnd.getZdMaterId()+"_"+gsEnd.getZdMaterModel()+"_"
					+gsEnd.getZdMaterSize()+"_"+gsEnd.getZdMaterColor()+"_"+gsEnd.getZdMaterQuanlity();*/
			String priceStr = gsEnd.getZdMaterId()+"_";
			priceStr = priceStr+(StringUtils.isEmpty(gsEnd.getZdMaterModel())?null:gsEnd.getZdMaterModel())+"_";
			priceStr = priceStr+(StringUtils.isEmpty(gsEnd.getZdMaterSize())?null:gsEnd.getZdMaterSize())+"_";
			priceStr = priceStr+(StringUtils.isEmpty(gsEnd.getZdMaterColor())?null:gsEnd.getZdMaterColor())+"_";
			priceStr = priceStr+(StringUtils.isEmpty(gsEnd.getZdMaterQuanlity())?null:gsEnd.getZdMaterQuanlity());
			if(priceMap==null){
				throw new SyBaseException("没有找到物料的平均价。");
			}
			//平均价
			BigDecimal priceAvg = priceMap.get(priceStr);
			if(priceAvg==null){
				priceAvg = BigDecimal.ZERO;
			}
			gsEnd.setZdAvgPrice(priceAvg);
			//入库总金额
			BigDecimal zdInSumMoney = gsEnd.getZdInSumMoney()==null?BigDecimal.ZERO:gsEnd.getZdInSumMoney();
			//盘点数量
			BigDecimal taskQuantity = gsEnd.getZdTaskQuantity()==null?BigDecimal.ZERO:gsEnd.getZdTaskQuantity();
			BigDecimal taskMoney = gsEnd.getZdTaskSumMoney()==null?BigDecimal.ZERO:gsEnd.getZdTaskSumMoney();
			if(pdEndMap!=null && pdEndMap.get(keyStr)!=null){
				LogicWarehouseEndMonthSumVO pdEndMonth = pdEndMap.get(keyStr);
				BigDecimal pdQuantity = pdEndMonth.getZdTaskQuantity()==null?BigDecimal.ZERO:pdEndMonth.getZdTaskQuantity();
				gsEnd.setZdTaskQuantity(pdQuantity.add(taskQuantity));
				BigDecimal pdSumMoney = gsEnd.getZdTaskSumMoney()==null?BigDecimal.ZERO:gsEnd.getZdTaskSumMoney();
				BigDecimal pdTotalMoney = pdSumMoney.add(taskMoney);
				pdTotalMoney = pdTotalMoney.setScale(p_scale, BigDecimal.ROUND_UP);
				gsEnd.setZdTaskSumMoney(pdTotalMoney);
			}else{
				gsEnd.setZdTaskQuantity(BigDecimal.ZERO);
				gsEnd.setZdTaskSumMoney(BigDecimal.ZERO);
			}
			//库存数量
			BigDecimal stockQuantity = gsEnd.getZdStockQuantity()==null?BigDecimal.ZERO:gsEnd.getZdStockQuantity();
			if(kcEndMap!=null&&kcEndMap.get(keyStr)!=null){
				LogicWarehouseEndMonthSumVO kcEndMonth = kcEndMap.get(keyStr);
				BigDecimal kcQuantity = kcEndMonth.getZdStockQuantity()==null?BigDecimal.ZERO:kcEndMonth.getZdStockQuantity();
				BigDecimal zdTotalQuantity = kcQuantity.add(stockQuantity);
				zdTotalQuantity = zdTotalQuantity.setScale(p_scale, BigDecimal.ROUND_UP);
				gsEnd.setZdStockQuantity(zdTotalQuantity);
				BigDecimal zdStockSumMoney = priceAvg.multiply(gsEnd.getZdStockQuantity());
				zdStockSumMoney = zdStockSumMoney.setScale(p_scale, BigDecimal.ROUND_UP);
				gsEnd.setZdStockSumMoney(zdStockSumMoney);
			}else{
				gsEnd.setZdStockQuantity(BigDecimal.ZERO);
				gsEnd.setZdStockSumMoney(BigDecimal.ZERO);
			}
			//出库总金额
			BigDecimal zdOutSumMoney = zdInSumMoney.subtract(gsEnd.getZdStockSumMoney());
			zdOutSumMoney = zdOutSumMoney.setScale(p_scale, BigDecimal.ROUND_UP);
			gsEnd.setZdOutSumMoney(zdOutSumMoney);
			endMonthMap.put(keyStr, gsEnd);
		}
		List<LogicWarehouseEndMonthSumVO> countList = new ArrayList<LogicWarehouseEndMonthSumVO>();
		if(pdEndMap==null){
			pdEndMap = new HashMap<String, LogicWarehouseEndMonthSumVO>();
		}
		for(String pdStr : pdEndMap.keySet()){
			if(pdStr==null||StringUtils.isBlank(pdStr)){
				continue;
			}
			LogicWarehouseEndMonthSumVO endMonth = endMonthMap.get(pdStr);
			if(endMonth==null){
				LogicWarehouseEndMonthSumVO _pdEndMonth = pdEndMap.get(pdStr);
				String zdMaterCode = _pdEndMonth.getZdMaterCode();
				_pdEndMonth.setZdMaterSery(materTypeMap.get(zdMaterCode)==null?null:materTypeMap.get(zdMaterCode).getZd002Name());
				_pdEndMonth.setZdInQuantity(BigDecimal.ZERO);
				_pdEndMonth.setZdInSumMoney(BigDecimal.ZERO);
				_pdEndMonth.setZdOutQuantity(BigDecimal.ZERO);
				_pdEndMonth.setZdOutSumMoney(BigDecimal.ZERO);
				_pdEndMonth.setZdStockQuantity(BigDecimal.ZERO);
				_pdEndMonth.setZdStockSumMoney(BigDecimal.ZERO);
				countList.add(_pdEndMonth);
			}else{
				continue;
			}
		}
		countList.addAll(gsEndList);
		rs.setRecordCount(countList.size());
		rs.setResults(countList);
		return rs;
	}

	/**
	 * 处理查询条件
	 * @param scs
	 */
	private SearchConditions processSearchCond(SearchConditions scs, Map<String, String> excelMap){
		excelMap.put("canQueryExcel", "0");
		SearchConditions processScs = new SearchConditions();
		processScs.setRemovedProperty("g.removed");
		List<SearchCondition> searchCondList = (List<SearchCondition>) scs.getConditions();
		for(SearchCondition searchCond : searchCondList){
			if(searchCond ==null){
				continue;
			}
			String fieldCond = searchCond.getField();
			if(StringUtils.isBlank(fieldCond)){
				continue;
			}
			if("g.zdStepDate".equals(fieldCond)){
				String zdFieldValue = searchCond.getValue()+"";
				if(StringUtils.isNotBlank(zdFieldValue)){
					if(zdFieldValue.trim().equals("2014-12")){
						excelMap.put("canQueryExcel", "1");
					}
					int condMonth[] = this.processQueryMonth(zdFieldValue);
					Date monthEnd = DateUtils.getMonthEnd(condMonth[0], condMonth[1], true);
					processScs.addCondition("g.zdStepDate", zdFieldValue.trim()+"-01 00:00:00", SearchCondition.OP_GREATER);
					processScs.addCondition("g.zdStepDate", DateUtils.toString(monthEnd, "yyyy-MM-dd HH:mm:ss"), SearchCondition.OP_SMALLER);
				}
			}else{
				processScs.addCondition(fieldCond, searchCond.getValue()+"", searchCond.getOperator());
			}
		}
		processScs.setPageNo(scs.getPageNo());
		processScs.setPageSize(scs.getPageSize());
		return processScs;
	}
	
	private int[] processQueryMonth(String condMonth){
		String[] condStr = condMonth.split("-");
		int[] condInt = new int[2];
		condInt[0] = new Integer(condStr[0].trim()).intValue();
		condInt[1] = new Integer(condStr[1].trim()).intValue();
		return condInt;
	}
	
	//取得物料当前平均价
	private Map<String, BigDecimal> processMaterAvgPrice(SearchConditions scs){
		SearchConditions avgScs = new SearchConditions();
		avgScs.setOrderBy(" bizCreatorDate desc, zd001MaterialsId desc, zd002WhId desc ");
		avgScs.setLimitPage(false);
		avgScs.setLimitClause(null);
		List<SearchCondition> condList = (List<SearchCondition>) scs.getConditions();
		for(SearchCondition cond : condList){
			String field = cond.getField();
			if("g.zdWhCode".equals(field)){
				continue;
			}
			if("g.zdMaterName".equals(field)){
				avgScs.addCondition("zd001MaterialsName", cond.getValue()+"", cond.getOperator());
			}
			if("g.zdMaterCode".equals(field)){
				avgScs.addCondition("zd001MaterialsCode", cond.getValue()+"", cond.getOperator());
			}
			if("g.zdStepDate".equals(field)){
				avgScs.addCondition("bizCreatorDate", cond.getValue()+"", cond.getOperator());
				avgScs.addCondition("bizCreatorDate", cond.getValue()+"", cond.getOperator());
			}
		}
		List<LogicWarehousePriceDetailsDO> priceList = logicWarehousePriceDetailsDAO.find(avgScs);
		if(priceList==null||priceList.isEmpty()||priceList.size()==0){
			return null;
		}else{
			Map<String, BigDecimal> priceMap = new HashMap<String, BigDecimal>();
			for(LogicWarehousePriceDetailsDO gsprice : priceList){
				if(gsprice==null||StringUtils.isBlank(gsprice.getId())){
					continue;
				}
				/*String keyStr = gsprice.getZd001MaterialsId()+"_"+gsprice.getZd001MaterialsModel()+"_"
						+gsprice.getZd001MaterialsSpec()+"_"+gsprice.getZd001MaterialsColor()+"_"+gsprice.getZd001MaterialsQuanlity();*/
				String keyStr = gsprice.getZd001MaterialsId()+"_";
				keyStr = keyStr + (StringUtils.isEmpty(gsprice.getZd001MaterialsModel())?null:gsprice.getZd001MaterialsModel())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(gsprice.getZd001MaterialsSpec())?null:gsprice.getZd001MaterialsSpec())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(gsprice.getZd001MaterialsColor())?null:gsprice.getZd001MaterialsColor())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(gsprice.getZd001MaterialsQuanlity())?null:gsprice.getZd001MaterialsQuanlity());
				BigDecimal zdPrice = gsprice.getZd007SumPrice()==null?BigDecimal.ZERO:gsprice.getZd007SumPrice();
				if(priceMap.get(keyStr)==null){
					priceMap.put(keyStr, zdPrice);
				}else{
					continue;
				}
			}
			return priceMap;
		}
	}
	
	//统计盘点数量(期初数量)
	private Map<String, LogicWarehouseEndMonthSumVO> processTaskToEndMonth(SearchConditions scs, String canQueryExcel){
		List<LogicWarehouseEndMonthSumVO> taskEndMonthList = new ArrayList<LogicWarehouseEndMonthSumVO>();
		if("1".equals(canQueryExcel)){
			//表示是2014-12月
			taskEndMonthList = logicWhCheckTaskDAO.findExcelQueryEndMonthToSummary(scs);
		}else{
			scs.setOrderBy(null);
			scs.setLimitPage(false);
			scs.setLimitClause(null);
			taskEndMonthList = logicWhCheckTaskDAO.findQueryEndMonthToSummary(scs);
		}
		if(taskEndMonthList==null||taskEndMonthList.isEmpty()||taskEndMonthList.size()==0){
			//如果没有查询到盘点数
			return null;
		}else{
			Map<String, LogicWarehouseEndMonthSumVO> taskEndMonthMap = new HashMap<String, LogicWarehouseEndMonthSumVO>();
			for(LogicWarehouseEndMonthSumVO taskEndMonth : taskEndMonthList){
				if(taskEndMonth==null){
					continue;
				}
				String keyStr = taskEndMonth.getZdWhId()+"_"+taskEndMonth.getZdMaterId()+"_";
				keyStr = keyStr + (StringUtils.isEmpty(taskEndMonth.getPiCode())?null:taskEndMonth.getPiCode())+"_";
				keyStr = keyStr + (StringUtils.isEmpty(taskEndMonth.getZdMaterModel())?null:taskEndMonth.getZdMaterModel())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(taskEndMonth.getZdMaterSize())?null:taskEndMonth.getZdMaterSize())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(taskEndMonth.getZdMaterColor())?null:taskEndMonth.getZdMaterColor())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(taskEndMonth.getZdMaterQuanlity())?null:taskEndMonth.getZdMaterQuanlity());
				LogicWarehouseEndMonthSumVO exEndMonth = taskEndMonthMap.get(keyStr);
				if(exEndMonth==null){
					taskEndMonthMap.put(keyStr, taskEndMonth);
				}else{
					BigDecimal taskQuantity = taskEndMonth.getZdTaskQuantity()==null?BigDecimal.ZERO:taskEndMonth.getZdTaskQuantity();
					exEndMonth.setZdTaskQuantity(taskQuantity.add(exEndMonth.getZdTaskQuantity()));
					BigDecimal taskSumMoney = taskEndMonth.getZdTaskSumMoney()==null?BigDecimal.ZERO:taskEndMonth.getZdTaskSumMoney();
					exEndMonth.setZdTaskSumMoney(taskSumMoney.add(taskEndMonth.getZdTaskSumMoney()));
				}
			}
			return taskEndMonthMap;
		}
	}
	//统计库存数量(期末数量)
	private Map<String, LogicWarehouseEndMonthSumVO> processInventoryToEndMonth(SearchConditions scs){
		scs.setOrderBy(null);
		scs.setLimitPage(false);
		scs.setLimitClause(null);
		scs.setRemovedProperty(null);
		List<LogicWarehouseEndMonthSumVO> wsEndMonthList = logicWarehouseInventoryDAO.findQueryEndMonthToSummary(scs);
		if(wsEndMonthList==null||wsEndMonthList.isEmpty()||wsEndMonthList.size()==0){
			return null;
		}else{
			Map<String, LogicWarehouseEndMonthSumVO> wsEndMonthMap = new HashMap<String, LogicWarehouseEndMonthSumVO>();
			for(LogicWarehouseEndMonthSumVO wsEndMonth : wsEndMonthList){
				if(wsEndMonth==null){
					continue;
				}
				/*String keyStr = wsEndMonth.getZdWhId()+"_"+wsEndMonth.getPiCode()+"_"+wsEndMonth.getZdMaterId()+"_"
						+wsEndMonth.getZdMaterModel()+"_"+wsEndMonth.getZdMaterSize()+"_"+wsEndMonth.getZdMaterColor()+"_"
						+wsEndMonth.getZdMaterQuanlity();*/
				String keyStr = wsEndMonth.getZdWhId()+"_"+wsEndMonth.getZdMaterId()+"_";
				keyStr = keyStr + (StringUtils.isEmpty(wsEndMonth.getPiCode())?null:wsEndMonth.getPiCode())+"_";
				keyStr = keyStr + (StringUtils.isEmpty(wsEndMonth.getZdMaterModel())?null:wsEndMonth.getZdMaterModel())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(wsEndMonth.getZdMaterSize())?null:wsEndMonth.getZdMaterSize())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(wsEndMonth.getZdMaterColor())?null:wsEndMonth.getZdMaterColor())+"_";
				keyStr = keyStr	+ (StringUtils.isEmpty(wsEndMonth.getZdMaterQuanlity())?null:wsEndMonth.getZdMaterQuanlity());
				LogicWarehouseEndMonthSumVO exEndMonth = wsEndMonthMap.get(keyStr);
				if(exEndMonth==null){
					wsEndMonthMap.put(keyStr, wsEndMonth);
				}else{
					BigDecimal zdStockQuantity = wsEndMonth.getZdStockQuantity()==null?BigDecimal.ZERO:wsEndMonth.getZdStockQuantity();
					exEndMonth.setZdStockQuantity(zdStockQuantity.add(exEndMonth.getZdStockQuantity()));
				}
			}
			return wsEndMonthMap;
		}
	}
}
